import services from '@/services/demo';
import { removeById } from '@/services/demo/ActivityController';
import {
  ActionType,
  FooterToolbar,
  PageContainer,
  ProColumns,
  ProDescriptions,
  ProDescriptionsItemProps,
  ProForm,
  ProTable,
} from '@ant-design/pro-components';
import { Button, Divider, Drawer, Input, message, Popconfirm, Upload } from 'antd';
import React, { useRef, useState } from 'react';
import { dateFormat } from '@/utils/format';
import ModalCard from '@/components/ModalCard';
import { queryAllNameAndTeacherId } from '@/services/demo/TeacherController';
import { URL_PREFIX } from '@/constants';
import { beforeUploadImg } from '@/utils/img';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { queryAllName } from '@/services/demo/AddressController';

const { queryList, add, remove, modify } =
  services.ActivityController;

/**
* 添加节点
* @param fields
*/
const handleAdd = async (fields: API.ActivityType) => {
  const hide = message.loading('正在添加');
  try {
    await add({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};
/**
 * 更新节点
 * @param fields
 */
const handleUpdate = async (fields: Partial<API.ActivityType>) => {
  const hide = message.loading('正在修改');
  try {
    await modify(
      { ...fields }
    );
    hide();
    message.success('修改成功');
    return true;
  } catch (error) {
    hide();
    message.error('修改失败请重试！');
    return false;
  }
};



const handleRemove = async (id: string) => {
  const hide = message.loading('正在删除');
  //console.log(selectedRows.map(item => item.rId))
  try {
    await removeById(id);
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};
const handleRemoveSelected = async (selectedRows: API.ActivityType[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  //console.log(selectedRows.map(item => item.rId))
  try {
    await remove({
      ids: selectedRows.map(item => item.rId)
    });
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};



function ActivityPage() {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] =
    useState<boolean>(false);
  const [updateFormValues, setUpdateFormValues] = useState({});
  const actionRef = useRef<ActionType>();
  const [row, setRow] = useState<API.ActivityType>();
  const [selectedRowsState, setSelectedRows] = useState<API.ActivityType[]>([]);

  const columns: ProColumns<API.ActivityType>[] = [
    {
      title: '活动封面图',
      dataIndex: 'rPicture',
      hideInSearch: true,
      width: 70,
      render: (_, record) => (<img src={record.rPicture}
        width="70"
        alt="活动封面图" />),
    },
    {
      title: '活动号',
      hideInSearch: true,
      hideInForm: true,
      width: 50,
      dataIndex: 'rId',
      tip: '活动号是唯一的 key',
    },
    {
      title: '活动名称',
      dataIndex: 'rName',
      width: 90,
      valueType: 'text',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '活动负责人',
      hideInSearch: true,
      width: 50,
      dataIndex: 'rT',
      valueType: 'text',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
      render: (_, record) => <span>{record.rT?.tName}</span>
    },
    {
      title: '活动地址',
      hideInSearch: true,
      width: 80,
      dataIndex: 'rAddressBody',
      valueType: 'text',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
      render: (_, record) => <span>{record.rAddressBody?.name}</span>
    },
    {
      title: '举办日期',
      hideInSearch: true,
      width: 70,
      sorter: true,
      dataIndex: 'rStarttime',
      valueType: 'dateTime',
      render: (_, record) => <span>{dateFormat(record.rStarttime)}</span>
    },
    {
      title: '操作',
      width: 100,
      hideInSearch: true,
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      render: (_, record) => (
        <>
          <Button type='primary'
            onClick={() => {
              handleUpdateModalVisible(true);
              setUpdateFormValues(record);
            }}
          >
            修改
          </Button>
          <Divider type="vertical" />
          <Popconfirm
            title="确定要删除吗？"
						onConfirm={async () => {
              const success = await handleRemove(record.rId)
              if (success) {
                actionRef.current?.reloadAndRest?.()
              }
            }}
            okText="确定"
            cancelText="取消"
          >
            <Button type='primary' danger >删除</Button>
          </Popconfirm>
        </>
      ),
    },
  ];

  const [imageUrl, setImageUrl] = useState<string>();
  const [loading, setLoading] = useState(false);
  const formColumns: ProColumns<API.ActivityType>[] = [
    {
      title: '活动号',
      dataIndex: 'rId',
      renderFormItem: () => <Input disabled/>
    },
    {
      title: '活动形式',
      dataIndex: 'rType',
      valueType: 'select',
      valueEnum: {
        2: '博雅读书',
        3: '博雅心情',
        4: '博雅实践',
        5: '博雅讲坛',
        6: '博雅修身',
        7: '博雅视野',
      }
    },
    {
      title: '活动名称',
      dataIndex: 'rName',
      valueType: 'text',
    },
    {
      title: '起始时间1',
      dataIndex: 'rStartTime',
      valueType: 'dateTime'
    },
    {
      title: '起始时间2',
      dataIndex: 'rStartTimeTwo',
      valueType: 'dateTime'
    },
    {
      title: '结束时间1',
      dataIndex: 'rEndTime',
      valueType: 'dateTime'
    },
    {
      title: '结束时间2',
      dataIndex: 'rEndTimeTwo',
      valueType: 'dateTime'
    },
    {
      title: '单场学分',
      dataIndex: 'rCredit',
      valueType: 'text'
    },
    {
      title: '活动人数',
      dataIndex: 'rMaxinum',
      valueType: 'digit'
    },
    {
      title: '参与导师',
      dataIndex: 'rTId',
      valueType: 'select',
      request: async () => {
        const res = await queryAllNameAndTeacherId();
        return res.data?.map((it: API.TeacherType) => ({
          label: `${it.tName}(工号 ${it.tTeacherid})`,
          value: it.tId,
        }))
      },
      params: {},
    },
    {
      title: '活动地址',
      dataIndex: 'rAddress',
      valueType: 'select',
      request: async () => {
        const res = await queryAllName();
        return res.data?.map((it: API.AddressType) => ({
          value: it.id,
          label: it.name
        }))
      },
      params: {},
    },
    {
      title: '可见学院',
      dataIndex: 'rZdcollege',
      valueType: 'select',
      valueEnum: {
        1: '全部学院',
        2: '商学院',
      }
    },
    {
      title: '可预约学院',
      dataIndex: 'rCollege',
      valueType: 'select',
      valueEnum: {
        '全部学院': '全部学院',
        '之江学院': '之江学院',
        '信息学院': '信息学院',
        '人文学院': '人文学院',
        '商学院': '商学院',
        '设计学院': '设计学院',
        '外国语学院': '外国语学院',
        '机械学院': '机械学院',
        '中旅学院': '中旅学院',
        '建筑学院': '建筑学院',
        '理学院': '理学院',
        '创新创业学院': '创新创业学院'
      }
    },
    {
      title: '活动封面图',
      dataIndex: 'rPicture',
      renderFormItem(item, { type, defaultRender, record }, form) {
        return (
          <ProForm.Item name="rPicture" valuePropName="data" getValueFromEvent={(e: any) => {
            console.log('Upload event:', e);
            const res = e?.file?.response?.data
            if (res && res.length > 0) {
              setImageUrl(URL_PREFIX + '/images/' + res)
              setLoading(false)
              
            } else {
              return form.getFieldValue(item.dataIndex!)
            }
            return URL_PREFIX + '/images/' + res;
          }} noStyle>
            <Upload
              name="file"
              listType="picture-card"
              className="avatar-uploader"
              showUploadList={false}
              action={URL_PREFIX + '/file/upload'}
              beforeUpload={beforeUploadImg}
            >
              {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : (
                <div>
                  {loading ? <LoadingOutlined /> : <PlusOutlined />}
                  <div style={{ marginTop: 8 }}>Upload</div>
                </div>
              )}
            </Upload>
          </ProForm.Item>
        )
      }
    },
    {
      title: '活动详情',
      dataIndex: 'rIntroduction',
      valueType: 'textarea'
    },
  ];

  return (
    <PageContainer
      header={{
        title: '活动',
      }}
    >
      <ProTable<API.ActivityType>
        headerTitle="所有活动"
        actionRef={actionRef}
        scroll={{ x: 1650 }}
        rowKey="rId"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            key="1"
            type="primary"
            onClick={() => handleModalVisible(true)}
          >
            新建
          </Button>,
        ]}
        request={queryList}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => setSelectedRows(selectedRows),
        }}
      />
      <ModalCard
        onCancel={() => {
          handleModalVisible(false)
          setImageUrl(undefined)
        }}
        modalVisible={createModalVisible}
      >
        <ProTable<API.ActivityType, API.ActivityType>
          onSubmit={async (value) => {
            const success = await handleAdd(value);
            if (success) {
              handleModalVisible(false);
              setImageUrl(undefined)
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          rowKey="tId"
          type="form"
          columns={formColumns}
        />
      </ModalCard>
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a>{' '}
              项&nbsp;&nbsp;
            </div>
          }
        >

          <Popconfirm
            title="确定要删除吗？"
            onConfirm={async () => {
              await handleRemoveSelected(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
            okText="确定"
            cancelText="取消"
          >
            <Button>批量删除</Button>
          </Popconfirm>
        </FooterToolbar>
      )}
      {updateFormValues && Object.keys(updateFormValues).length ? (
        <ModalCard
          onCancel={() => {
            handleUpdateModalVisible(false)
            setUpdateFormValues({})
            setImageUrl(undefined)
          }}
          modalVisible={updateModalVisible}
        >
          <ProTable<API.ActivityType, API.ActivityType>
            form={{ initialValues: updateFormValues }}
            onSubmit={async (value) => {
              const success = await handleUpdate(value);
              if (success) {
                handleUpdateModalVisible(false);
                setUpdateFormValues({})
                setImageUrl(undefined)
                if (actionRef.current) {
                  actionRef.current.reload();
                }
              }
            }}
            rowKey="rId"
            type="form"
            columns={formColumns}
          />
        </ModalCard>
      ) : null}

      <Drawer
        width={600}
        visible={!!row}
        onClose={() => {
          setRow(undefined);
        }}
        closable={false}
      >
        {row?.rId && (
          <ProDescriptions<API.ActivityType>
            column={2}
            title={row?.rId}
            request={async () => ({
              data: row || {},
            })}
            params={{
              id: row?.rId,
            }}
            columns={columns as ProDescriptionsItemProps<API.ActivityType>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default ActivityPage;

